package com.mjk.service.system;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.mjk.common.biz.BaseBiz;
import com.mjk.common.util.NumberUtil;
import com.mjk.constant.AdminCommonConstant;
import com.mjk.mapper.info.UserMapper;
import com.mjk.mapper.system.BaseGroupMapper;
import com.mjk.mapper.system.MenuMapper;
import com.mjk.mapper.system.ResourceAuthorityMapper;
import com.mjk.model.system.BaseGroup;
import com.mjk.model.system.Menu;
import com.mjk.model.system.ResourceAuthority;
import com.mjk.vo.AuthorityMenuTree;
import com.mjk.vo.GroupUsers;


@Service
public class BaseGroupService extends BaseBiz<BaseGroupMapper, BaseGroup>{
	
	@Autowired
	private BaseGroupMapper baseGroupMapper;
	@Autowired
	private MenuMapper menuMapper;
	@Autowired
	private ResourceAuthorityMapper resourceAuthorityMapper;
	@Autowired
    private UserMapper userMapper;
	
	public List<BaseGroup> getAll(BaseGroup city) {
	     return baseGroupMapper.selectAll();
	}
	
	/**
	 * 获取群主(group)关联的菜单
	 * @param groupId
	 * @return
	 */
	public List<AuthorityMenuTree> getAuthorityMenu(int groupId){
		List<AuthorityMenuTree> list = new ArrayList<AuthorityMenuTree>();
		AuthorityMenuTree node = null;
		List<Menu> menus = menuMapper.selectMenuByAuthorityId(String.valueOf(groupId), AdminCommonConstant.AUTHORITY_TYPE_GROUP);
		for (Menu menu : menus) {
			node = new AuthorityMenuTree();
			node.setText(menu.getTitle());
			BeanUtils.copyProperties(menu, node);
			list.add(node);
		}
		return list;
	}
	
	/**
	 * 获取菜单下的资源
	 * @param groupId
	 * @return
	 */
	public List<Integer> getAuthorityElement(int groupId){
		List<Integer> ids = new ArrayList<Integer>();
		ResourceAuthority authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_BTN);
		authority.setAuthorityId(groupId);
		List<ResourceAuthority> list = resourceAuthorityMapper.select(authority);
		for (ResourceAuthority resourceAuthority : list) {
			ids.add(resourceAuthority.getResourceId());
		}
		return ids;
	}
	
	/**
     * 变更群组关联的菜单
     * @param groupId
     * @param menus
     */
	public void editAuthorityMenu(int groupId, String[] menus){
		// 1、删除群组关联的菜单
		resourceAuthorityMapper.deleteByAuthorityIdAndResourceType(groupId, AdminCommonConstant.RESOURCE_TYPE_MENU);
		
		// 2、查询所有的菜单
		List<Menu> menuList = menuMapper.selectAll();
        Map<String,String> map = new HashMap<String, String>();
        for(Menu menu:menuList){
            map.put(menu.getId().toString(),menu.getParentId().toString());
        }
        Set<String> relationMenus = new HashSet<String>();
        relationMenus.addAll(Arrays.asList(menus));
        ResourceAuthority authority = null;
        // 3、查询子菜单的父菜单，并添加到relationMenus
        for(String menuId:menus){
            findParentID(map,relationMenus,menuId);
        }
        for(String menuId:relationMenus){
            authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_MENU);
            authority.setAuthorityId(groupId);
            authority.setResourceId(NumberUtil.parseInteger(menuId));
            authority.setParentId(-1);
            resourceAuthorityMapper.insertSelective(authority);
        }
	}
	
	 /**
     * 分配资源权限
     * @param groupId
     * @param menuId
     * @param elementId
     */
    public void editAuthorityElement(int groupId,int menuId,int elementId){
        ResourceAuthority authority = new ResourceAuthority(AdminCommonConstant.AUTHORITY_TYPE_GROUP, AdminCommonConstant.RESOURCE_TYPE_BTN);
        authority.setAuthorityId(groupId);
        authority.setResourceId(elementId);
        authority.setParentId(-1);
        resourceAuthorityMapper.insertSelective(authority);
    }
    
    /**
     * 移除资源权限
     * @param groupId
     * @param menuId
     * @param elementId
     */
    public void removeAuthorityElement(int groupId, int menuId, int elementId) {
        ResourceAuthority authority = new ResourceAuthority();
        authority.setAuthorityId(groupId);
        authority.setResourceId(elementId);
        authority.setParentId(-1);
        resourceAuthorityMapper.delete(authority);
    }
	
	/**
	 * 查询子菜单的父菜单
	 * @param map   所有的菜单<id，父id>
	 * @param relationMenus   关联的菜单
	 * @param id  当前菜单id
	 */
	private void findParentID(Map<String,String> map,Set<String> relationMenus,String id){
        String parentId = map.get(id);
        if(String.valueOf(AdminCommonConstant.ROOT).equals(id)){
            return ;
        }
        relationMenus.add(parentId);
        findParentID(map,relationMenus,parentId);
    }
	
	 /**
     * 获取群组关联用户
     * @param groupId
     * @return
     */
    public GroupUsers getGroupUsers(int groupId) {
        return new GroupUsers(userMapper.selectMemberByGroupId(groupId), userMapper.selectLeaderByGroupId(groupId));
    }
    
    /**
     * 变更群主所分配用户
     * @param groupId
     * @param members
     * @param leaders
     */
    public void editGroupUsers(int groupId, String members, String leaders){
    	baseGroupMapper.deleteGroupLeadersById(groupId);
    	baseGroupMapper.deleteGroupMembersById(groupId);
        if(!StringUtils.isEmpty(members)){
            String[] mem = members.split(",");
            for(String m:mem){
                mapper.insertGroupMembersById(groupId,Integer.parseInt(m));
            }
        }
        if(!StringUtils.isEmpty(leaders)){
            String[] mem = leaders.split(",");
            for(String m:mem){
                mapper.insertGroupLeadersById(groupId,Integer.parseInt(m));
            }
        }
    }
}
